/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.khh.base.util;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;


public class FileClassLoader extends ClassLoader {

    private String classPath;

    public FileClassLoader(String classPath) {
        this.classPath = classPath;
    }

    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            byte[] classBytes = null;
            classBytes = this.loadClassBytes();
            Class clazz = this.defineClass(name, classBytes, 0,classBytes.length);

            if (clazz == null)
                throw new ClassNotFoundException(name);

            return clazz;

        } catch (FileNotFoundException ex) {
            throw new ClassNotFoundException(name);
        } catch (IOException ex) {
            throw new ClassNotFoundException(name);
        }
    }

    private byte[] loadClassBytes() throws FileNotFoundException, IOException {
        FileInputStream in = null;
        try {
            in = new FileInputStream(classPath);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();

            int ch;
            while ((ch = in.read()) != -1) {
                byte b = (byte) (ch);
                buffer.write(b);
            }
            in.close();
            return buffer.toByteArray();
        } finally {
            in.close();
        }
    }
}
